import {Component, ElementRef, Input, OnInit, ViewChild} from '@angular/core';
import {DraftUserDto} from "../../dto/DraftUserDto";
import {AuthService} from "../../service/auth.service";
import {MatFormField, MatLabel, MatPrefix, MatSuffix} from "@angular/material/form-field";
import {MatIcon} from "@angular/material/icon";
import {MatInput} from "@angular/material/input";
import {MatButton, MatFabButton} from "@angular/material/button";
import {MatOption, MatSelect} from "@angular/material/select";
import {FormControl, FormGroup, FormsModule, ReactiveFormsModule, Validators} from "@angular/forms";
import {NgForOf, NgIf} from "@angular/common";
import {OAuthService} from "angular-oauth2-oidc";
import {Router} from "@angular/router";
import {Subscription} from "rxjs";
import {NgxMaskDirective} from "ngx-mask";
import {lawyerSpec} from "../../dto/LawyerSpec";
import {MatCheckbox} from "@angular/material/checkbox";
import {
  MatCard, MatCardActions,
  MatCardContent,
  MatCardHeader, MatCardImage,
  MatCardLgImage,
  MatCardMdImage,
  MatCardSubtitle, MatCardTitle,
  MatCardTitleGroup
} from "@angular/material/card";


@Component({
  selector: 'app-cabinet',
  standalone: true,
  imports: [
    MatFormField,
    MatIcon,
    MatInput,
    MatButton,
    MatLabel,
    MatSelect,
    FormsModule,
    MatOption,
    NgIf,
    MatSuffix,
    MatPrefix,
    NgxMaskDirective,
    NgForOf,
    MatCheckbox,
    MatFabButton,
    MatCard,
    MatCardLgImage,
    MatCardMdImage,
    MatCardHeader,
    MatCardTitleGroup,
    MatCardSubtitle,
    MatCardTitle,
    MatCardContent,
    MatCardActions,
    MatCardImage,
    ReactiveFormsModule,
  ],
  templateUrl: './cabinet.component.html',
  styleUrl: './cabinet.component.scss'
})
export class CabinetComponent implements OnInit {
  // @Input() draftUserDto?: DraftUserDto
  @ViewChild('inputPic') inputPicRef?: ElementRef




  user = {
    firstName: '',
    lastName: '',
    middleName: '',
    login: '',
    phone: '',
    email: '',
    roleUser: '',
    securityUserId: ''

  }

  userData = new FormGroup({
    firstName: new FormControl('', Validators.required),
    lastName: new FormControl('', Validators.required),
    middleName: new FormControl(''),
    phone: new FormControl('', Validators.required),
    email: new FormControl('', Validators.required),
    lawyerRegistrationNumber: new FormControl('', Validators.required),

  })

  getUserSubscription: Subscription | undefined
  lawyerRegistrationNumber =  ''
  lawyerSpecifications  = lawyerSpec
  selectedSpec  =  ['']
  selectedType = ''
  selectedValue = ''
  userType = [
    {value: 'CLIENT', valueView: 'Клиент'},
    {value: 'LAWYER', valueView: 'Адвокат'},
    {value: 'PSYCHOLOGIST', valueView: 'Психолог'},
  ]

  image?: File
  imagePreview: string | ArrayBuffer | null = ''

  constructor(private authService: AuthService, private oauthService: OAuthService, private router: Router) {
    // if (!this.oauthService.hasValidAccessToken()) {
    //   this.router.navigate(['/']).then(r => true)
    // this.oauthService.initLoginFlow()
    // }
  }

  ngOnInit(): void {
    this.getUserSubscription = this.authService.getUser().subscribe(response => {
      console.log(response)
      // this.draftUserDto = response
      this.user.firstName = response.firstName
      this.user.lastName = response.lastName
      this.user.middleName  = response.middleName
      // this.user.login = response.login
      // this.user.email = response.email
      // this.user.phone = response.phone
      this.user.roleUser = response.userRole
      this.user.securityUserId = response.securityUserId
      this.userData.controls.firstName.setValue(response.firstName)
      this.userData.controls.lastName.setValue(response.lastName)
      this.userData.controls.middleName.setValue(response.middleName)
      this.userData.controls.phone.setValue(response.phone)
      this.userData.controls.email.setValue(response.email)
    })
    console.log(this.user)
    console.log(this.inputPicRef)
  }

  sendUserData() {
    this.selectedSpec = this.getSelectedCheckbox()
    let user = {
      firstName: this.userData.get(['firstName'])?.value,
      lastName: this.userData.get(['lastName'])?.value,
      middleName: this.userData.get(['middleName'])?.value,
      email: this.userData.get(['email'])?.value,
      phone: this.userData.get(['phone'])?.value,
      roleUser: this.selectedType,
      lawyerSpecification: this.selectedSpec,
      lawyerRegistrationNumber: this.userData.get(['lawyerRegistrationNumber'])?.value,
    }
    console.log((user))
    this.getSelectedCheckbox()
    this.authService.saveUser(user, this.image)
  }

  getSelectedCheckbox()  {
    return this.lawyerSpecifications
      .filter(element  =>  element.selected)
      .map(element   =>  element.value)

  }

  triggerPic() {
    console.log('Жмакнули загрузить триггер пик')
    console.log(this.inputPicRef)
    this.inputPicRef?.nativeElement.click()


  }

  onFileUpload(event: any) {
    console.log('Жмакнули onfile Upload')

    const file  =  event.target.files[0]
    this.image  = file
    const reader = new FileReader()
    reader.onload = () =>  {
      this.imagePreview  =  reader.result
    }
    reader.readAsDataURL(file)
  }

  editPic() {
    console.log('Жмакнули editPic')
    console.log(this.inputPicRef)
    if (this.inputPicRef?.nativeElement === undefined) {
      console.log(this.inputPicRef + ' Нажали едит')
    }

    this.image = undefined
    this.imagePreview = ''
  }

  getSelectedValue() {
    console.log('выбрали пользователя')
    this.selectedValue  =  this.userType
      .filter(element => element.value === this.selectedType)
      .map(element  =>  element.valueView)[0]
    console.log(this.selectedValue)
  }
}
